﻿using mozhi.smarterp.Business.Sales.Repositories;
using Mozhi.Abp.Domain.BasicData;
using Mozhi.Abp.Domain.BasicData.Repositories;
using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.Business.Sales.Services
{
    public class SaleProductPriceManager : DomainService
    {
        private IProductRepository _productRepository;
        private ICurrencyRepository _currencyRepository;
        private ITaxRateRepository _taxRateRepository;
        private ICustomerRepository _customerRepository;
        private IGuidGenerator _guidGenerator;
        private ISaleProductPriceRepository _repository;

        public SaleProductPriceManager(ISaleProductPriceRepository repository , IProductRepository productRepository, ICurrencyRepository currencyRepository, ITaxRateRepository taxRateRepository, ICustomerRepository customerRepository,
            IGuidGenerator guidGenerator)
        {
            _repository = repository;
            _productRepository = productRepository;
            _currencyRepository = currencyRepository;
            _taxRateRepository = taxRateRepository;
            _customerRepository = customerRepository;
            _guidGenerator = guidGenerator;
        }

        public async Task<SaleProductPrice> GetAsync(Guid? id, string code, string name, Guid? customerId, Guid currencyId, bool includeTax)
        {
            var count = await _repository.GetCountAsync(null, code, null, null, null, id) + await _repository.GetCountAsync(null, null, name, null, null, id);

            if (count > 0)
                throw new UserFriendlyException($"编码{code}或者名称：{name}已经存在", "100000");

            SaleProductPrice productPrice;
            var customer = customerId.HasValue ? await _customerRepository.GetAsync(customerId.Value) : null;
            var currency = await _currencyRepository.GetAsync(currencyId);

            if (id.HasValue)
            {
                productPrice = await _repository.GetAsync(id.Value);

                productPrice.Change(code, name, customer, currency, includeTax);
            }
            else
                productPrice = new SaleProductPrice(_guidGenerator.Create(), code, name, customer, currency, includeTax);

            return productPrice;
        }

        public async Task<SaleProductPriceItem> GetItemAsync(Guid? id, Guid productId, decimal? minQuantity, decimal? maxQuantity, decimal price, Guid? taxRateId,
            DateTime effectiveDate, DateTime expirationDate)
        {
            var product = await _productRepository.GetAsync(productId);

            var taxRate = taxRateId.HasValue ? await _taxRateRepository.GetAsync(taxRateId.Value) : null;

            id = id ?? _guidGenerator.Create();

            return new SaleProductPriceItem(id.Value, product, minQuantity, maxQuantity, price, taxRate, effectiveDate, expirationDate);
        }
    }
}
